
import { Button, Modal } from 'antd';
import { useState } from "react";
import { CheckBox, ProgressBar } from 'devextreme-react';
import { intl } from "@/utils";
import { msgError } from '@/pages/msg';
import { getNestApiData } from '@/services/cpasRequest';


export const ConvertOnlineButton: React.FC<API.ConvertOnlineProps> = (props) => {
    const [open, setOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [contentHintArray, setContentHintArray] = useState<string[]>([]);
    const [progressMax, setprogressMax] = useState(100); //进度最大值
    const [isReserveLocal, setIsReserveLocal] = useState<boolean>(true); //是否保留本地项目
    const [convertOnlineDataArray, setConvertOnlineDataArray] = useState<API.ConvertOnlineData[]>([])
    const [progressInfo, setProgressInfo] = useState<API.ProgressInfo>(
        {
            progressText: '',
            progressValue: 0,
        },
    );
    //打开窗口事件
    async function openButtonClick() {
        setProgressInfo({ progressText: '', progressValue: 0, })
        const tmpConvertOnlineDataArray: API.ConvertOnlineData[] = await props.getConvertOnlineDataArray();
        if (tmpConvertOnlineDataArray.length == 0) {
            return msgError(`错误,还没有选择组成组成部分还没有选择项目.`);
        }
        const zcbfIsSelfArray: string[] = tmpConvertOnlineDataArray.filter(item => {
            return item.onlinePart.sjxmbh == item.localPart.sjxmbh
                && item.onlinePart.zcbfid == item.localPart.zcbfid
        }).map(item => item.onlinePart.zcbfName);
        if (zcbfIsSelfArray.length > 0) {
            return msgError(`以下 ${zcbfIsSelfArray.length} 个组成部分不能选择自己:` + zcbfIsSelfArray.join('、'))
        }
        //提示数据
        const contentHintArray: string[] = [];
        for (let i = 0; i < tmpConvertOnlineDataArray.length; i++) {
            const convertOnlineData = tmpConvertOnlineDataArray[i];
            const noStr = tmpConvertOnlineDataArray.length == 1 ? '' : (i + 1) + '、';
            contentHintArray.push(noStr + convertOnlineData.localPart.zcbfName
                + ' => ' + convertOnlineData.onlinePart.zcbfName);
            if (contentHintArray.length >= 10) {
                break;
            }
        }
        contentHintArray.push(` 转为联机项目,共 ${tmpConvertOnlineDataArray.length} 个,是否继续?`);
        setContentHintArray(contentHintArray);
        setConvertOnlineDataArray(tmpConvertOnlineDataArray);
        setOpen(true);
    }
    //开始转换
    async function startConvertClick(): Promise<void> {
        const total = convertOnlineDataArray.length;
        setprogressMax(total + 1);
        const startTime = performance.now();
        for (let i = 0; i < total; i++) {
            const convertOnlineData: API.ConvertOnlineData = convertOnlineDataArray[i];
            convertOnlineData.isReserveLocal = isReserveLocal;
            const { localPart, onlinePart } = convertOnlineData;

            updateProgressInfo(i + 1, `正在转换 ${i + 1}/${total}, ${localPart.zcbfName}=>${onlinePart.zcbfName}`);
            const oneRetData = await getNestApiData('/project/convertToOnline', '', { ...convertOnlineData });

            if (!oneRetData.ok) {
                updateProgressInfo(i + 1, oneRetData.data);
                Modal.error({
                    content: intl('pro.convertError', '转换失败 {msg}', { msg: oneRetData.data }),
                    onOk() { },
                    okText: intl('pub.ok', '确定'),
                });
                return;
            }
        }
        props.onFinished(true);//完成后刷新
        updateProgressInfo(total + 1, '转换完成');
        const endTime = performance.now();
        const takeSeconds = '，耗时 ' + ((endTime - startTime) / 1000).toFixed(0) + ' 秒。';
        if (!isReserveLocal) {//如果不保留时,表未删除本地项目,要刷新
            PubSub.publish('projectTreeRefresh', { msg: 'projectRefresh' });
            PubSub.publish('zcbfidsTreeRefresh', { msg: 'zcbfidsRefresh' });
        }
        Modal.info({
            content: intl('pro.convertFinish', '转换完成 {msg}', { msg: takeSeconds }),
            onOk: () => { setOpen(false); },
            okText: intl('pub.ok', '确定'),
        });

    }
    //进度数据
    const updateProgressInfo = (progressValue: number, //进度数据[0..100]   
        progressText?: string, //进度说明
    ) => {
        progressText = progressText;
        setProgressInfo({ progressValue, progressText });
    };
    return <>
        <Button onClick={openButtonClick}
            disabled={props.disabled}
            style={{
                paddingLeft: 0,
                paddingRight: 0,
                display: props.showConvertOnline ? "" : "none"
            }} >{intl('pro.exceuteConvet', '执行转换')}</Button>
        {open && (

            <Modal
                //centered
                //open={open}
                width={800}
                visible={open}
                title={'转为联机项目: ' + props.projectCode}
                onOk={startConvertClick}
                onCancel={() => setOpen(false)}
                maskClosable={false} //点击蒙层是否允许关闭
                footer={[
                    <span style={{ float: 'left' }}>
                        <CheckBox
                            value={isReserveLocal}
                            onValueChange={(value: boolean) => setIsReserveLocal(value)}
                            text={intl('pro.reserveLocalZcbf', '保留原项目')}
                            hint={intl('pro.reserveLocalZcbfHint', '不选中项目将被删除',)}
                        />
                    </span>,
                    <Button key="back" onClick={() => setOpen(false)} disabled={loading}>
                        {intl('pub.cancel', '取消')}
                    </Button >,
                    <Button
                        key="submit"
                        type="primary"
                        loading={loading}
                        onClick={startConvertClick}
                    >
                        {intl('pro.startConvert', '开始转换')}
                    </Button>,
                    <span style={{ marginRight: 20 }}></span>,
                ]}
            >
                {contentHintArray.map(str => <div>{str}</div>)}
                <div style={{ height: 40 }}>
                    <ProgressBar
                        style={{ marginTop: '10px' }}
                        visible={
                            progressInfo.progressValue > 0 &&
                            progressInfo.progressValue <= progressMax
                        }
                        width={'99%'}
                        height={40}
                        value={progressInfo.progressValue}
                        showStatus={true}
                        min={0}
                        max={progressMax}
                        statusFormat={(ratio: number, value: number) => {
                            return `已完成 ${(ratio * 100).toFixed(0)}% 　${progressInfo.progressText
                                } `;
                        }}
                    />
                </div>
            </Modal >
        )}
    </>
}